export function drawImage(
  dataView,
  imageData,
  width,
  height,
  targetX,
  targetY,
  bWidth,
  totalLength
) {
  for (let i = 0; i < height; i++) {
    const yPos = targetY + i;
    for (let j = 0; j < width; j++) {
      const xPos = targetX + j;
      for (let k = 0; k < 3; k++) {
        // bgr
        const pos = getBytePos(bWidth, yPos, xPos) + k;
        if (pos < totalLength)
          dataView.setInt8(
            pos,
            imageData[i * (width * 4) + (j + 1) * 4 - 2 - k],
            true
          );
      }
    }
  }
}

export function createBMP(width, height, depth = 24) {
  const head = 0x36;
  const bWidth = ((width * depth + 31) & ~31) / 8;
  const body = bWidth * height;
  const length = body + head;
  const buffer = new ArrayBuffer(length);
  const dataView = new DataView(buffer);
  //00-01  设置BM文件头
  dataView.setInt16(0, 0x424d, false);
  //02-05  设置文件大小校验
  dataView.setInt32(2, length, true);
  //06-09  保留位
  //0A-0D  设置位图信息偏移位
  dataView.setInt32(0xa, 0x36, true);
  //0E-11  设置信息头大小
  dataView.setInt32(0xe, 0x28, true);
  //12-15  设置图像宽度
  dataView.setInt32(0x12, width, true);
  //16-19  设置图像高度
  dataView.setInt32(0x16, -height, true);
  //1A-1B  定值1
  dataView.setInt8(0x1a, 0x1, true);
  //1C-1D  设置像素深度（24位）
  dataView.setInt8(0x1c, depth, true);
  //1E-21  图像不压缩
  dataView.setInt32(0x1e, 0, true);
  //22-25  图像大小，设置为0
  dataView.setInt32(0x22, 0, true);
  //26-29  水平分辨率，缺省为0
  dataView.setInt32(0x26, 0, true);
  //2A-2D  垂直分辨率，缺省为0
  dataView.setInt32(0x2a, 0, true);
  //2E-31  颜色数256
  dataView.setInt32(0x2e, 0x100, true);
  //32-35  重要颜色索引数0 都重要
  dataView.setInt32(0x32, 0x100, true);

  return { dataView, buffer, bWidth, length };
}
// function wrtieByte(dataView, data, pos) {
//   dataView.setInt8(pos, data, true);
// }
function getBytePos(bWidth, i, j, depth = 24) {
  const pos = 0x36 + (j * depth) / 8 + i * bWidth;
  return pos;
}
